/**
 * 
 */
package bible.sunflower.work.yinfeng.db2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author zhangyp
 *
 */
public class BudgetAdjust {
	
	public static Connection getConnection(){
		Connection con = null;
		try {
			Class.forName("com.ibm.db2.jcc.DB2Driver");
			String ip ="32.188.32.87";
			String user = "db2admin";
			String password = "123456";
			String port = "50000";
			String url = "jdbc:db2://" + ip + ":" + port + "/hoyi";
			con = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return con;
	}
	
	public static void execute(Connection con, Statement stmt, ResultSet rs){
		String tableName = "budgetadjust1";
		try {
			rs = stmt.executeQuery("select count('*') from " + tableName );
			if( rs.next() ){
				System.out.println( "count is " + rs.getInt(1) );
			}
			PreparedStatement pstmt = con.prepareStatement("select * from ? where id = (select min(id) from ?) and mainflag is null ");
			pstmt.setString(1, tableName);
			pstmt.setString(2, tableName);			
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				System.out.println( "id is " + rs.getLong("id"));
			}
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				System.out.println( "id is " + rs.getLong("id"));
			}
			pstmt.close();
		} catch ( SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void clean(Connection con, Statement stmt, ResultSet rs){
		try {
			if( rs != null ){
				rs.close();
			}
			if( stmt != null ){
				stmt.close();
			}
			if( con != null && !con.isClosed() ){
				con.close();
			}
		} catch ( SQLException e) {
			e.printStackTrace();
		}		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("---START---");
		Connection con = getConnection();
		ResultSet rs = null;
		try {
			Statement stmt = con.createStatement();
			execute( con, stmt, rs);
			clean( con, stmt, rs );
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("---END---");
	}

}
